package com.jason.kotlin.activityresult

import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.jason.kotlin.R
import com.jason.kotlin.model.ActivityResultEntity
import com.jason.kotlin.utils.showToast
import kotlinx.android.synthetic.main.fragment_a.*


/**
 * Description:
 *
 * @author chenbaoyang
 * @create 2021/1/14 17:39
 */
class FragmentA : Fragment() {


    private lateinit var observer: MyLifecycleObserver

    companion object {
        fun newInstance(): FragmentA {
            return FragmentA()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        observer = MyLifecycleObserver(requireActivity().activityResultRegistry,
            object : ActivityResultListener {
                override fun callBack(resultEntity: ActivityResultEntity) {
                    val data = resultEntity.data
                    when (resultEntity.key) {
                        MyLifecycleObserver.KEY_GET_CONTENT -> showToast(data.toString())
                        MyLifecycleObserver.KEY_OPEN_DOCUMENT -> showToast(data.toString())
                        MyLifecycleObserver.KEY_REQUEST_PERMISSION -> {
                            if (data as Boolean) {
                                showToast("granted permission")
                            } else {
                                showToast("denied permission")
                            }
                        }
                        MyLifecycleObserver.KEY_REQUEST_MULTI_PERMISSION -> {
                            var text = StringBuilder()
                            (data as Map<*, *>).forEach {
                                text.append(it.key).append("授权")
                                if (it.value as Boolean) {
                                    text.append("成功")
                                } else {
                                    text.append("失败")
                                }
                            }
                            showToast(text.toString())
                        }

                        MyLifecycleObserver.KEY_TAKE_PICTURE_PREVIEW -> {
                            activity?.let {
                                Glide.with(it).load(resultEntity.data as Bitmap)
                                    .placeholder(R.drawable.yurisa__001).into(image)
                            }!!
                        }

                        MyLifecycleObserver.KEY_TAKE_PICTURE -> {
                            if (data is Boolean) {
                                if (data) {
                                    showToast("保存成功")
                                } else {
                                    showToast("保存失败")
                                }
                            }

                        }

                        MyLifecycleObserver.KEY_TAKE_VIDEO -> {
                            activity?.let {
                                Glide.with(it).load(resultEntity.data)
                                    .placeholder(R.drawable.yurisa__001).into(image)
                            }!!
                        }

                        MyLifecycleObserver.KEY_PICK_CONTACT -> {
                            val cursor = activity?.contentResolver?.query(resultEntity.data as Uri, null, null, null, null)
                            cursor?.run {
                                if(cursor.moveToFirst()){
                                    val nameFieldColumnIndex =
                                        cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
                                    var numberFieldColumnIndex =
                                        cursor.getColumnIndex("phonenumber")
                                    if(numberFieldColumnIndex == -1) {
                                        numberFieldColumnIndex = cursor.getColumnIndex("number")
                                    }
                                    val name = cursor.getString(nameFieldColumnIndex)
                                    val number =
                                        cursor.getString(numberFieldColumnIndex)
                                    showToast(name + "---" +number)
                                }
                            }

                        }
                    }
                }

            })
        lifecycle.addObserver(observer)
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return LayoutInflater.from(activity).inflate(R.layout.fragment_a, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        selectImageButton.setOnClickListener {
            observer.selectImage()
        }

        selectFileButton.setOnClickListener {
            observer.selectFile()
        }

        permissionButton.setOnClickListener {
            observer.requestPermission(android.Manifest.permission.READ_PHONE_STATE)
        }

        multiPermissionButton.setOnClickListener {
            observer.requestMultiPermission(
                arrayOf(
                    android.Manifest.permission.READ_PHONE_STATE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.CAMERA,
                    android.Manifest.permission.READ_CONTACTS,
                    android.Manifest.permission.WRITE_CONTACTS
                )
            )
        }

        takePicturePreviewButton.setOnClickListener {
            observer.takePicturePreview()
        }

        takePictureButton.setOnClickListener {
            activity?.let { it1 -> observer.takePicture(it1) }
        }

        takeVideoButton.setOnClickListener {
            activity?.let { it1 -> observer.takeVideo(it1) }
        }

        pickContactButton.setOnClickListener {
            observer.pickContact()
        }
    }

    override fun onDestroy() {
        lifecycle.removeObserver(observer)
        super.onDestroy()
    }

}